<template>
  <div class="editor-con">
    <div ref="toolbar" class="toolbar">
    </div>
    <div ref="textcon" class="textcon" :style="{height: height}">
    </div>
  </div>
</template>

<script>
import wangeditor from 'wangeditor'
import config from 'api/config'
import {commonUpload} from 'api/commonApi'
export default {
  model: {
    prop: 'content',
    event: 'change'
  },
  props: {
    content: {
      default: ''
    },
    height: {
      default: '300px'
    }
  },
  data() {
    return {
    }
  },
  watch: {
    content: {
      handler: function(val) {
        if(this.editor && this._content !== val){
          this.insertHTML(val)
        }
      }
    }
  },
  methods: {
    handleChange (html){
      this._content = html
      this.$emit('change', html)
    },
    // 启用或者禁用
    changeEditorStatus(val) {
      this.editor.$textElem.attr('contenteditable', val)
    },
    insertHTML(con) {
      this.editor.txt.html(con)
    },
    upImg(files, insert){
      let myfiles = Array.from(files)
      myfiles.forEach(async (file) => {
        if(file.size>5*1024*1024){
          alert('上传文件只能为5M内')
        }else{
          commonUpload(file).then(res => {
            if(res) {
              insert(config.imgUrl+res)
            }else{
              this.$message({
                message: '上传出错',
                type: 'error'
              })
            }
          })
        }
      })
    },
    editorInit(){
      this.editor = new wangeditor(this.$refs.toolbar, this.$refs.textcon)
      this.editor.customConfig.pasteFilterStyle = false
      this.editor.customConfig.onchange = this.handleChange
      this.editor.customConfig.customUploadImg = this.upImg
      this.editor.customConfig.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
          'quote',  // 引用
          'emoticon',  // 表情
          'image',  // 插入图片
          'table',  // 表格
          'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
      ]
      this.editor.create()
      if(this.content) {
        this.insertHTML(this.content)
      }
    }
  },
  mounted(){
    this.editorInit()
  }
}
</script>

<style lang="scss" scoped>
.editor-con{
  width: 100%;
}
.toolbar{
  display: flex;
  flex-wrap: wrap;
  border: 1px solid #ccc;
  border-bottom: none;
}
.textcon{
  border: 1px solid #ccc;
}
</style>
